<script>
import axios from "axios";

export default {
  name: 'ChatPageView',
  data() {
    return {

      inputText: '',
      messages: [
        { sender: 'user', avatar: this.userAvatar, content: this.$route.params.doctorName +'医生您好，请问您近期有时间来做上门随访吗?' },
        { sender: 'doctor', avatar: this.$route.params.imageUrl, content: '这周五上午您方便吗?' },
        { sender: 'user', avatar: this.userAvatar, content: '方便的' }
      ],
      sessionId: null


    }
  },
  methods: {

    GoToNext(){
      this.$router.push({ name: 'ChatSettings'});
    },
    goBack() {
      this.$router.push({ name: 'Consultation' });
    },

    sendMessage() {
      if (!this.inputText.trim()) return

      // 添加用户消息
      this.messages.push({
        sender: 'user',
        avatar: this.userAvatar, // 使用从后端获取的用户头像
        content: this.inputText
      })

      // 添加初始空白AI消息
      const botMessage = {
        sender: 'doctor',
        avatar: this.$route.params.imageUrl,//医生头像
        content: ''
      }
      this.messages.push(botMessage)
      const botMessageIndex = this.messages.length - 1

      // 使用EventSource接收SSE数据
      const eventSource = new EventSource(
          //ai的访问路径
          `http://localhost:9001/user/streamAssistant/streamWithContext?message=${encodeURIComponent(this.inputText)}&sessionId=${this.sessionId}`
      )

      eventSource.onmessage = (event) => {
        this.messages[botMessageIndex].content += event.data
        this.$set(this.messages, botMessageIndex, {...this.messages[botMessageIndex]})
        this.scrollToBottom()
      }

      eventSource.onerror = () => {
        console.error("SSE连接错误")
        eventSource.close()
        this.messages[botMessageIndex].content += '\n'
        this.scrollToBottom()
      }

      this.inputText = ''
      this.scrollToBottom()
    },

    scrollToBottom() {
      this.$nextTick(() => {
        const container = this.$refs.messagesContainer
        container.scrollTop = container.scrollHeight
      })
    },

    handleIconClick() {
      alert(`点击了图标`)
    },

    // 新增方法：从后端获取用户头像
    async fetchUserAvatar() {
      try {
        const response = await axios.get('http://localhost:10086/api/user/user/getByIdUserImage') // 替换为实际的后端API
        this.userAvatar = response.data.data.data
        console.log(JSON.stringify(response.data.data.data))
        // 更新现有消息中的用户头像
        this.messages.forEach(msg => {
          if (msg.sender === 'user') {
            msg.avatar = this.userAvatar
          }
        })
      } catch (error) {
        console.error('获取用户头像失败:', error)
        // 设置默认头像或处理错误
        this.userAvatar = '/default-user-avatar.png'
      }
    },


  },
  created() {
    if (!localStorage.getItem('sessionId')) {
      localStorage.setItem('sessionId', Math.random().toString(36).substring(2, 15))
    }
    this.sessionId = localStorage.getItem('sessionId')
    this.fetchUserAvatar() // 组件创建时获取用户头像
    localStorage.setItem('doctorName', JSON.stringify(this.$route.params.doctorName)) //医生名称
    localStorage.setItem('position', JSON.stringify(this.$route.params.position)) //医生职位
    localStorage.setItem('imageUrl', JSON.stringify(this.$route.params.imageUrl)) //医生头像
  }

}

</script>

<template>
  <div class="chat-container">
    <!-- 头部 -->
    <div class="ChatPageHeader">
      <div class="ChatPageHeader-left" @click="goBack">
        <svg class="ServiceMessagesIcon" viewBox="0 0 1024 1024" width="30" height="30">
          <path d="M333.994667 469.333333H853.333333v85.333334H333.994667l228.864 228.864-60.330667 60.330666L170.666667 512l331.861333-331.861333 60.330667 60.330666L333.994667 469.333333z"/>
        </svg>
      </div>
      <span class="ChatPageHeaderSpan">聊天</span>
      <div class="ChatPageHeader-right" @click="GoToNext">
        <svg class="ServiceMessagesIcon" viewBox="0 0 1024 1024" width="30" height="30">
          <path d="M594.466 454.588c0-37.137 23.484-68.813 56.252-81.374-7.646-30.584-19.66-59.529-35.499-86.29-32.222 14.2-70.997 8.193-97.212-18.022-26.214-26.214-32.221-64.99-18.022-97.211a363.318 363.318 0 0 0-86.289-35.499c-12.561 32.768-44.237 56.252-81.374 56.252-37.137 0-68.813-23.484-81.374-56.252-30.583 7.646-59.528 19.66-86.289 35.499 14.2 32.222 8.192 70.997-18.022 97.211s-64.99 32.222-97.212 18.023c-15.838 26.76-27.853 55.705-35.499 86.289 32.768 12.56 56.252 44.237 56.252 81.374 0 37.137-23.484 68.813-56.252 81.374 7.646 30.583 19.661 59.528 35.5 86.289 32.22-14.2 70.996-8.192 97.21 18.022 26.215 26.214 32.223 64.99 18.023 97.212 26.76 15.838 55.706 27.853 86.29 35.498 12.56-32.768 44.236-56.251 81.373-56.251 37.137 0 68.813 23.483 81.374 56.251 30.583-7.645 59.529-19.66 86.29-35.498-14.2-32.222-8.193-70.998 18.021-97.212 26.215-26.214 64.99-32.222 97.212-18.022 15.838-26.76 27.853-55.706 35.499-86.29-32.768-12.56-56.252-43.69-56.252-81.373z m-262.144 87.381c-48.06 0-87.381-39.322-87.381-87.381s39.321-87.382 87.381-87.382 87.381 39.322 87.381 87.382-39.321 87.381-87.38 87.381z m359.356-369.732h318.396v80.281H691.678z m0 323.31h318.396v80.282H691.678zM175.582 818.86h834.492v80.281H175.582z"/>
        </svg>
      </div>
    </div>

    <!-- 聊天内容区域 -->
    <div class="chat-content" ref="messagesContainer">
      <div
          v-for="(msg, index) in messages"
          :key="index"
          class="message-wrap"
          :class="{ 'user-message': msg.sender === 'user' }"
      >
        <div class="ChatPageAvatar" :style="{ backgroundImage: `url(${msg.avatar})` }"></div>
        <div class="bubble" :class="{ 'user-bubble': msg.sender === 'user' }">
          <div class="text">{{ msg.content }}</div>
        </div>
      </div>
    </div>


    <!-- 底部输入区域 -->
    <div class="input-area">
      <div class="InputAreaLeft" @click="handleIconClick">
        <svg class="LeftIcon" viewBox="0 0 1024 1024" width="30" height="30">
          <path d="M544 830.4V960h-64v-129.6c-161.6-16-288-152.8-288-318.4h64c0 140.8 115.2 256 256 256s256-115.2 256-256h64c0 165.6-126.4 302.4-288 318.4zM512 640c70.4 0 128-57.6 128-128V192c0-70.4-57.6-128-128-128s-128 57.6-128 128v320c0 70.4 57.6 128 128 128z"/>
        </svg>
      </div>

      <div class="input-wrapper">
        <input
            v-model="inputText"
            type="text"
            placeholder="请输入消息"
            @keyup.enter="sendMessage">
        <button class="send-btn" :class="{ active: inputText.trim() }" @click="sendMessage">发送</button>
      </div>

      <div class="InputAreaRight" @click="handleIconClick">
        <svg class="RightIcon" viewBox="0 0 1024 1024" width="30" height="30">
          <path d="M896 160H128v704h768z m-704 64h640v423.68L706.08 496l-157.12 157.12L352 358.24l-160 240z m0 576v-86.24l160-240 187.04 280.48L701.92 592 832 747.52V800z"/>
          <path d="M672 448a96 96 0 1 0-96-96 96 96 0 0 0 96 96z m0-128a32 32 0 1 1-32 32 32 32 0 0 1 32-32z"/>
        </svg>
      </div>
    </div>


  </div>
</template>

<style scoped>
@import "ChatPage.css";
</style>